package com.sciencep.pro.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sciencep.pro.common.config.Constant;
import com.sciencep.pro.common.domain.OscaConstant;
import com.sciencep.pro.common.domain.QueryRequest;
import com.sciencep.pro.common.domain.ResponseResult;
import com.sciencep.pro.common.utils.SortUtil;
import com.sciencep.pro.core.dao.BranchContactMapper;
import com.sciencep.pro.core.domain.dto.branch.BranchTO;
import com.sciencep.pro.core.domain.dto.user.UserDetail;
import com.sciencep.pro.core.domain.dto.workdailylog.WorkdailyLogTO;
import com.sciencep.pro.core.domain.entity.Branch;
import com.sciencep.pro.core.domain.entity.BranchContact;
import com.sciencep.pro.core.domain.entity.ProBaseInfo;
import com.sciencep.pro.core.domain.entity.ProContact;
import com.sciencep.pro.core.domain.vo.branch.BranchVO;
import com.sciencep.pro.core.service.IBranchContactService;
import com.sciencep.pro.core.service.IBranchService;
import com.sciencep.pro.core.service.IProBaseInfoService;
import com.sciencep.pro.core.service.IProContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Sciencep
 */
@Service
@Transactional
public class BranchContactServiceImpl extends ServiceImpl<BranchContactMapper, BranchContact> implements IBranchContactService {

    @Autowired
    @Lazy
    private IBranchService branchService;

    @Autowired
    @Lazy
    private IBranchContactService branchContactService;

    @Autowired
    @Lazy
    private IProBaseInfoService proBaseInfoService;

    @Autowired
    @Lazy
    private IProContactService proContactService;


    @Override
    public Page<BranchTO> getBranchList(QueryRequest queryRequest) {
        Page<WorkdailyLogTO> page = new Page<>();
        SortUtil.handlePageSort(queryRequest, page, "id", OscaConstant.ORDER_DESC, false);
        log.debug("test");
        return baseMapper.getBranchList(page);
    }

    @Override
    public ResponseResult<Branch> addBranch(BranchVO branchVO, UserDetail userDetail) {
        ResponseResult<Branch> responseResult = new ResponseResult<>();
        if (branchVO == null) {
            responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_NULL);
            return responseResult;
        }
        if (branchService.getOne(new LambdaQueryWrapper<Branch>().eq(Branch::getDataName, branchVO.getDataName()).eq(Branch::getIsDel, Constant.IsDelete.NO)) != null) {
            responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_REPEAT);
            return responseResult;
        }
        if (!CollUtil.isNotEmpty(branchVO.getBranchContactList())) {
            responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_PROCESS_ERROR);
            return responseResult;
        } else {
            for (int i = 0; i < branchVO.getBranchContactList().size() && CollUtil.isNotEmpty(branchVO.getBranchContactList()); i++) {
                if (branchVO.getBranchContactList().get(i).getContactName() == null){
                    return new ResponseResult<Branch>().failure(Constant.ErrorCode.SYSTEM_ERROR,Constant.ErrorMessage.CONTACT_NAME_REPEAT);
                }
            }
            //生成contactId
            for (BranchContact branchContact : branchVO.getBranchContactList()) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");//设置日期格式
                String date = simpleDateFormat.format(new Date());
                branchContact.setContactId(date);
                while (branchContactService.getOne(new LambdaQueryWrapper<BranchContact>().eq(BranchContact::getContactId, date)) != null) {
                    String date1 = simpleDateFormat.format(new Date());
                    branchContact.setContactId(date1);
                }
            }
        }
        //主表
        Branch branch = new Branch();
        branch.setDataName(branchVO.getDataName());
        branch.setCreateUserId(userDetail.getUserId());
        branch.setCreateUserName(userDetail.getUserName());
        branchService.save(branch);
        Long branchId = branch.getId();

        //从表
        if (CollUtil.isNotEmpty(branchVO.getBranchContactList())) {
            List<BranchContact> branchContactList = new ArrayList<>();
            branchVO.getBranchContactList().forEach(e -> {
                BranchContact branchContact = new BranchContact();
                branchContact.setBranchID(branchId.toString());
                branchContact.setContactId(e.getContactId());
                branchContact.setContactName(e.getContactName());
                branchContact.setCreateUserId(userDetail.getUserId());
                branchContact.setCreateUserName(userDetail.getUserName());
                branchContactList.add(branchContact);
            });
            branchContactService.saveBatch(branchContactList);
        }
        responseResult.success();
        return responseResult;
    }

    @Override
    public ResponseResult<Branch> deleteBranch(String id, UserDetail userDetail) {
        try {
            if ("".equals(id)) {
                return new ResponseResult<Branch>().failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_ID_NULL);
            }
        } catch (java.lang.NullPointerException e){
            return new ResponseResult<Branch>().failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_ID_NULL);
        }
        if (CollUtil.isNotEmpty(proBaseInfoService.list(new LambdaQueryWrapper<ProBaseInfo>().eq(ProBaseInfo::getBranchId, id)))) {
            return new ResponseResult<Branch>().failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_PROCEED);
        }
        Branch branch = new Branch();
        branch.setIsDel(Constant.IsDelete.YES);
        branch.setModifyUserId(userDetail.getUserId());
        branch.setModifyUserName(userDetail.getUserName());
        BranchContact branchContact = new BranchContact();
        branchContact.setIsDel(Constant.IsDelete.YES);
        branchContact.setModifyUserId(userDetail.getUserId());
        branchContact.setModifyUserName(userDetail.getUserName());
        branchService.update(branch, new LambdaQueryWrapper<Branch>().eq(Branch::getId, id));
        branchContactService.update(branchContact, new LambdaQueryWrapper<BranchContact>().eq(BranchContact::getBranchID, id));
        return new ResponseResult<Branch>().success();
    }

    @Override
    public ResponseResult<Branch> updateBranch(BranchVO branchVO, UserDetail userDetail) {
        ResponseResult<Branch> responseResult = new ResponseResult<>();
        if (branchVO == null) {
            responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_NULL);
            return responseResult;
        }
        if (branchService.getOne(new LambdaQueryWrapper<Branch>().eq(Branch::getDataName, branchVO.getDataName()).eq(Branch::getIsDel, Constant.IsDelete.NO).
                ne(Branch::getId, branchVO.getId())) != null) {
            responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_REPEAT);
            return responseResult;
        }
        //分社名称被项目使用
        if (CollUtil.isNotEmpty(proBaseInfoService.list(new LambdaQueryWrapper<ProBaseInfo>().eq(ProBaseInfo::getBranchId, branchVO.getId())))) {
            //分社名称不能修改
            if (!branchService.getById(branchVO.getId()).getDataName().equals(branchVO.getDataName())) {
                responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_PROCEED_EDIT);
                return responseResult;
            }
            //分社成员不可减少
            for (BranchContact branchContact : branchContactService.list(new LambdaQueryWrapper<BranchContact>().eq(BranchContact::getBranchID, branchVO.getId()).eq(BranchContact::getIsDel, Constant.IsDelete.NO))) {
                boolean reduce = false;
                for (ProContact proContact : proContactService.list(new LambdaQueryWrapper<ProContact>().eq(ProContact::getContactId, branchContact.getContactId()).last("limit 1"))) {
                    if (branchContact.getContactId().equals(proContact.getContactId())) {
                        for (BranchContact branchContactPage : branchVO.getBranchContactList()) {
                            if (branchContact.getContactId().equals(branchContactPage.getContactId())) {
                                reduce = true;
                                break;
                            }
                        }
                    }
                    if (!reduce) {
                        responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_PROCEED_EDIT_CONTACT);
                        return responseResult;
                    }
                }
            }
        }
        if (!CollUtil.isNotEmpty(branchVO.getBranchContactList())) {
            responseResult.failure(Constant.ErrorCode.SYSTEM_ERROR, Constant.ErrorMessage.BRANCH_PROCESS_ERROR);
            return responseResult;
        } else {
            for (int i = 0; i < branchVO.getBranchContactList().size() && CollUtil.isNotEmpty(branchVO.getBranchContactList()); i++) {
                if (branchVO.getBranchContactList().get(i).getContactName() == null){
                    return new ResponseResult<Branch>().failure(Constant.ErrorCode.SYSTEM_ERROR,Constant.ErrorMessage.CONTACT_NAME_REPEAT);
                }
            }
            //生成contactId
            for (BranchContact branchContact : branchVO.getBranchContactList()) {
                if (null == branchContactService.getOne(new LambdaQueryWrapper<BranchContact>().eq(BranchContact::getBranchID, branchVO.getId()).eq(BranchContact::getContactId, branchContact.getContactId()).eq(BranchContact::getIsDel, Constant.IsDelete.NO))) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");//设置日期格式
                    String date = simpleDateFormat.format(new Date());
                    branchContact.setContactId(date);
                    while (branchContactService.getOne(new LambdaQueryWrapper<BranchContact>().eq(BranchContact::getContactId, date)) != null) {
                        String date1 = simpleDateFormat.format(new Date());
                        branchContact.setContactId(date1);
                    }
                }
            }
        }
        Branch branch = new Branch();
        branch.setDataName(branchVO.getDataName());
        branch.setModifyUserId(userDetail.getUserId());
        branch.setModifyUserName(userDetail.getUserName());
        branchService.update(branch, new LambdaQueryWrapper<Branch>().eq(Branch::getId, branchVO.getId()));

        if (CollUtil.isNotEmpty(branchVO.getBranchContactList())) {
            //先全部删除
            BranchContact branchContactDel = new BranchContact();
            branchContactDel.setIsDel(Constant.IsDelete.YES);
            branchContactService.update(branchContactDel, new LambdaQueryWrapper<BranchContact>().eq(BranchContact::getBranchID, branchVO.getId()));

            List<BranchContact> branchInsertContactList = new ArrayList<>();
            List<BranchContact> branchUpdateContactList = new ArrayList<>();
            branchVO.getBranchContactList().forEach(e -> {

                BranchContact branchContactCompare = branchContactService.getOne(new LambdaQueryWrapper<BranchContact>().
                        eq(BranchContact::getContactId, e.getContactId()).eq(BranchContact::getBranchID, branchVO.getId()));

                BranchContact branchContact = new BranchContact();
                if (null == branchContactCompare) {
                    branchContact.setBranchID(branchVO.getId());
                    branchContact.setContactId(e.getContactId());
                    branchContact.setContactName(e.getContactName());
                    branchContact.setCreateUserId(userDetail.getUserId());
                    branchContact.setCreateUserName(userDetail.getUserName());
                    branchInsertContactList.add(branchContact);
                } else {
                    branchContact.setId(branchContactCompare.getId());
                    branchContact.setContactName(e.getContactName());
                    branchContact.setIsDel(Constant.IsDelete.NO);
                    branchContact.setModifyUserId(userDetail.getUserId());
                    branchContact.setModifyUserName(userDetail.getUserName());
                    branchUpdateContactList.add(branchContact);
                }
            });
            if (CollUtil.isNotEmpty(branchInsertContactList)) {
                branchContactService.saveBatch(branchInsertContactList);
            }
            if (CollUtil.isNotEmpty(branchUpdateContactList)) {
                branchContactService.updateBatchById(branchUpdateContactList);
            }
        }
        responseResult.success();
        return responseResult;
    }

    @Override
    public List<BranchContact> getContactByProId(String proId, String branchId) {


        return baseMapper.getContactByProId(proId, branchId);
    }
}
